<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属企业" prop="entId" v-if="userId === 1">
        <el-select v-model="queryParams.entId" placeholder="请选择所属企业">
          <el-option
            v-for="item in entOptions"
            :key="item.id"
            :label="item.entName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否平台设置" prop="adminFlag">
        <el-select v-model="queryParams.adminFlag" placeholder="请选择是否平台设置" clearable>
          <el-option
            v-for="dict in dict.type.sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.wms_process_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wms:process:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wms:process:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wms:process:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="processList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="名称" align="center" prop="name" :show-overflow-tooltip="true"/>
      <el-table-column label="所属公司" align="center" prop="entName" :show-overflow-tooltip="true"/>
      <el-table-column label="是否平台设置" align="center" prop="adminFlag">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.adminFlag"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wms_process_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.entId = entId"
            v-hasPermi="['wms:process:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="scope.row.entId = entId"
            v-hasPermi="['wms:process:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-setting"
            @click="handleSetting(scope.row)"
            v-if="scope.row.entId = entId"
            v-hasPermi="['wms:process:edit']"
          >设置节点</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改流程对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-loading="btnLoading">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 设置流程节点对话框 -->
    <el-dialog title="设置流程节点" :visible.sync="openDetail" width="500px" append-to-body>
      <el-card class="box-card" style="margin-bottom: 10px" shadow="never" v-for="(node,index) in processNodes">
        <div slot="header" class="clearfix">
          <span>节点{{index + 1}}</span>
          <el-button type="danger" icon="el-icon-delete" @click="deleNode(index)" circle style="float: right; padding: 3px 0;width: 22px;"></el-button>
        </div>
        <el-form label-width="80px">
          <el-form-item label="节点类型" prop="name">
            <el-select
              v-model="node.type"
              placeholder="节点类型"
              clearable
              style="width: 240px"
              @change="handleProcessTypeChange"
            >
              <el-option
                v-for="dict in typeDict"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
                :disabled="dict.disable"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="是否审核" prop="name">
            <el-radio-group v-model="node.ifAudit">
              <el-radio
                v-for="dict in dict.type.sys_yes_no"
                :key="dict.value"
                :label="dict.value"
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </el-card>
      <div style="display: flex;justify-content: center">
        <el-button type="primary" icon="el-icon-plus" @click="handleAddNode" v-if="processNodes.length <= dict.type.sys_yes_no.length">添加节点</el-button>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormDetail" v-loading="btnLoading">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProcess, getProcess, delProcess, addProcess, updateProcess } from "@/api/wms/process";
import {addDetail, listDetail} from "@/api/wms/processDetail";
import {listEntXlk} from "@/api/wms/ent";

export default {
  name: "Process",
  dicts: ['sys_yes_no','wms_process_type','wms_process_status'],
  data() {
    return {
      //按钮加载
      btnLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 流程表格数据
      processList: [],
      // 单位下拉框
      entOptions: [],
      // 流程节点
      processNodes: [],
      //物流类型数据源
      typeDict: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openDetail: false,
      userId: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        entId: null,
        adminFlag: null,
        status: null
      },
      // 表单参数
      form: {},
      // 选中的数据
      rows: [],
      // 表单校验
      rules: {
        name: [
          { required: true, message: "流程名称不能为空", trigger: "blur" },
          { max: 50, message: '流程名称长度最长50字符', trigger: 'blur' }
        ],
      },
      processId: null,
      //企业id
      entId: null
    };
  },
  created() {
    this.userId = this.$store.getters.id
    this.entId = this.$store.getters.entId
    this.getList();
    this.getEntList();
  },
  methods: {
    /** 查询流程列表 */
    getList() {
      this.loading = true;
      listProcess(this.queryParams).then(response => {
        this.processList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询企业 */
    getEntList() {
      listEntXlk().then(response => {
        console.log(response.data)
        this.entOptions = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openDetail = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.rows = selection
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加流程";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      if (row.id) {
        if (row.entId != this.entId) {
          this.$message.error("不可修改平台设置的流程")
          return
        }
      } else {
        let arr =this.rows.filter(item => item.entId != this.entId)
        if (arr.length > 0) {
          this.$message.error("不可修改平台设置的流程")
          return
        }
      }
      const id = row.id || this.ids
      getProcess(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改流程";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.btnLoading = true
          if (this.form.id != null) {
            updateProcess(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(f => {
              this.btnLoading = false
            });
          } else {
            addProcess(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(f => {
              this.btnLoading = false
            });
          }
        }
      });
    },
    /** 提交按钮 */
    submitFormDetail() {
      let sign = -1
      for (let i = 0; i < this.processNodes.length; i++) {
        let node = this.processNodes[i];
        if (!node.type) {
          sign = i + 1
          break
        }
      }
      if (sign === -1 && this.processNodes.length > 0) {
        this.btnLoading = true
        addDetail(this.processNodes).then(response => {
          if (response.code == 200) {
            this.$modal.msgSuccess("新增成功");
            this.openDetail = false;
            this.getList();
          } else {
            this.$message.error(response.msg);
          }
        }).finally(f => {
          this.btnLoading = false
        });
      } else {
        if (this.processNodes.length === 0) {
          this.$message.error("节点为空，不可保存")
        } else {
          this.$message.error("节点" + sign + "未设置类型，不可保存")
        }
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if (row.id) {
        if (row.entId != this.entId) {
          this.$message.error("不可删除平台设置的流程")
          return
        }
      } else {
        let arr =this.rows.filter(item => item.entId != this.entId)
        if (arr.length > 0) {
          this.$message.error("不可删除平台设置的流程")
          return
        }
      }
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除流程编号为"' + ids + '"的数据项？').then(function() {
        return delProcess(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 设置节点按钮操作 */
    handleSetting(row) {
      this.processId = row.id
      //todo 查询流程详情
      listDetail({processId: row.id}).then(res => {
        this.processNodes = res.data
        this.typeDict = this.dict.type.wms_process_type
        this.handleProcessTypeChange()
        this.openDetail = true;
      })
    },
    //添加节点
    handleAddNode(){
      this.processNodes.push({
        processId: this.processId,
        ifAudit: 'Y'
      });
    },
    // 删除节点
    deleNode(index){
      this.processNodes.splice(index, 1)
    },
    //去除重复节点
    handleProcessTypeChange(val){
      let types = []
      this.processNodes.forEach(item => {
        if (item.type) {
          types.push(item.type)
        }
      })
      this.typeDict.forEach(item => {
        if (types.indexOf(item.value) > -1) {
          item.disable = true
        } else {
          item.disable = false
        }
      })
    }
  }
};
</script>
